<template>
  <div class="echarts">
    <ECharts :option="option" />
  </div>
</template>

<script setup lang="ts" name="BarEcharts">
// import { ECOption } from "@/components/ECharts/config";
import ECharts from "@/components/ECharts/index.vue";
import { onMounted, reactive, watch } from "vue";

const props = defineProps({
  data: {
    type: Array as () => any,
    required: false,
    default: () => []
  },
  color: {
    type: Array as () => string[],
    required: false,
    default: () => []
  },
  loading: {
    type: Boolean,
    required: false,
    default: () => false
  }
});
let defaultColor = reactive<string[]>(["#ff8d1a", "#FFC300", "#0ACAD1", "#339CFF"]);
const option: any = reactive({
  tooltip: {
    trigger: "item",
    confine: true
  },
  series: [
    {
      name: "总数",
      type: "pie",
      center: ["50%", "50%"],
      radius: ["55%", "70%"],
      avoidLabelOverlap: false,
      label: {
        show: true,
        position: "center",
        rich: {
          a: {
            color: "rgba(42, 130, 228, 0.8)",
            fontSize: 20,
            padding: 4,
            fontWeight: "600"
          },
          b: {
            // color: "rgba(0, 0, 0, 0.8)",
            fontSize: 14,
            fontWeight: "400"
          }
        },
        formatter: () => {
          return "{a|0}\n{b|总数}";
        }
      },
      emphasis: {
        label: {
          show: false
        },
        itemStyle: {
          opacity: 1
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
});

const setOption = () => {
  const dataList: any = [];
  let colorList: string[] = [];
  let total = 0;
  if (props.data && props.data.length) {
    props.data.forEach((item, index) => {
      total += item.count;
      dataList.push({
        value: parseInt(item.count),
        name: item.level,
        label: {
          show: true
        },
        color: defaultColor[index]
      });
    });
    colorList = defaultColor;
  } else {
    // 无数据
    dataList.push({
      value: 0,
      name: "总数",
      label: {
        show: true
      }
    });
    colorList.push("#D3D3D3");
  }
  option.series[0].data = dataList;
  // option.series[0].text = total
  option.series[0].label.formatter = function () {
    return "{a|" + total + "}\n{b|总数}";
  };
  console.log(total);
  option.color = colorList;
};
watch(
  () => props.data,
  () => {
    setOption();
  },
  { deep: true, immediate: true }
);
watch(
  () => props.color,
  newVal => {
    newVal && newVal.length ? (defaultColor = [...newVal]) : (defaultColor = [...defaultColor]);
    setOption();
  },
  { deep: true, immediate: true }
);
onMounted(() => {
  setOption();
});
</script>

<style scoped lang="scss">
.echarts {
  width: 100%;
  height: 100%;
}
</style>
